<?php
namespace Api\Model;
use Think\Model;
class VcodeModel extends Model {

    /**
     * @name 根据手机号检查验证码状态
     * @param $mobile
     * @param $type
     * @return $return
     */
    public function verifyVcodeStatus($mobile,$type){
        $ctime=$this->where(" `mobile` = '{$mobile}' and `type`={$type}")->order('id desc')->getField('ctime');
        if($ctime){
            if($ctime+60 < time() ){
                $return=C('VCODE_STATUS.INVALID');
            }else{
                $return=C('VCODE_STATUS.VALID');
            }
        }else{
            $return=C('VCODE_STATUS.INEXISTENCE');
        }
        return $return;
    }

    /**
     * @name 验证手机验证码
     * @param $mobile
     * @param $vcode
     * @param $type
     */
    public function verifyVcode($mobile,$vcode,$type){
        $result=$this->verifyVcodeStatus($mobile,$type);
        $realVcode=$this->where(" `mobile` = '{$mobile}' and `type`={$type}")->order('id desc')->getField('vcode');
        if($result === C('VCODE_STATUS.VALID')){
            if($realVcode==$vcode){
                $return=C('VERIFY_VCODE.RIGHT');
            }else{
                $return=C('VERIFY_VCODE.INVALID');
            }
        }else{
            $return=C('VERIFY_VCODE.ERROR');
        }
        return $return;
    }
    /**
     * @name 新增验证码
     * @param $mobile
     * @param $type
     * @return bool
     */
   public function addVcode($mobile,$type){
        if($this->verifyVcodeStatus($mobile,$type)===C('VCODE_STATUS.VALID')){
            return false;
        }else{
            $securityCode=makeSecurityCode(C('VCODE_LENGTH'));
       
            $this->where("`mobile`={$mobile} and `type`={$type}")->delete();
            $data=array(
                'mobile'=>$mobile,
                'vcode'=>$securityCode,
                'type'=>$type,
                'ctime'=>time()
            );
            $this->add($data);
            return $securityCode;
        }
   }

}